package com.hyc.Serializer;

import com.hyc.message.MessageType;
import com.hyc.message.RpcRequest;
import com.hyc.message.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.AllArgsConstructor;

/**
 * @author 冷环渊
 * @date 2025/6/4 11:28
 * 用于netty的自定义编码器
 * @description MyEncoder
 */
@AllArgsConstructor
public class MyEncoder extends MessageToByteEncoder {
    private Serializer serializer;

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
//        System.out.println("进入编码器的对象" + o.getClass());
        //判断请求的类型
        if (o instanceof RpcRequest) {
            byteBuf.writeShort(MessageType.REQUEST.getCode());
        } else if (o instanceof RpcResponse) {
            byteBuf.writeShort(MessageType.RESPONSE.getCode());
        }
        //写入序列化器的类型
        byteBuf.writeShort(serializer.getType());
        //将对象转换为数组
        byte[] res = serializer.serialize(o);
        byteBuf.writeInt(res.length);
        byteBuf.writeBytes(res);
    }
}
